package com.google.code.sysarch.v1.e31;

import javax.swing.*;

class iThread extends Thread {
	
	public static Scheduler myScheduler;
	private JProgressBar progressBar;
	private boolean running = false;
	private int initialWork = 0;
	private int work = 0;
	private int timeslice = 1000;
	
	iThread(int work) {
		this.work = work;
		this.initialWork = work;
	}
	
	public void run() {
	
		/* This block is synchronized, but only to its own thread object
			More than one thread may be working concurrently within this block
		*/
		synchronized (this) {
			while (this.work > 0) {
				if (this.running) {
					calculate();
					this.updateProgress();
				} else {
					myScheduler.queue(this);
					try {
						this.wait();
					} catch (InterruptedException e) { }
				}
			}
		}
		/* call the Scheduler */
		myScheduler.interrupt();
	}
	
	/* the scheduler will call this method to allow/disallow the thread to run */
	public void setRunning(boolean run) {
		this.running = run;
	}
	
	/* Do some stupid work */
	public void calculate() {
		this.work--;
		calcPrimes(10000);
	}
	
	/* calculates primes without saving the results, how stupid is that??? */
	public void calcPrimes(int n) {
		for (int i = 0; i < n; i++) {
			isPrime(i);
		}
	}
	
	/* Returns true when number is a prime number */
	public boolean isPrime(int number) {
		int root = (int) Math.ceil(Math.sqrt(number));
		if (number == 2) { return true; }
		if ((number & 1) == 0) { return false; }
		for (int div = 3; div <= root; div++) {
			if (number % div == 0) { return false; }
		}
		return true;
	}
	
	/* functions to set and get the timeslice this threads uses */
	public void setTimeslice(int timeslice) {
		this.timeslice = timeslice;
		if (this.timeslice < Scheduler.MIN_TIMESLICE) {
			this.timeslice = Scheduler.MIN_TIMESLICE;
		}		
	}
	
	public int getTimeslice() {
		return this.timeslice;
	}
	
	public void updateProgress() {
		int progress = (int) Math.floor(100.0f * (this.initialWork - this.work) / this.initialWork);
		this.progressBar.setValue(progress);
	}
	
	public void setProgressBar(JProgressBar p) {
		this.progressBar = p;
	}
	
}